/**
 * File: StartupCurtainCheck.java
 * Created by: mhaimel
 * Created on: 16 Jul 2009
 * CVS:  $Id: StartupCurtainCheck.java,v 1.1 2009/08/05 15:16:12 mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.general;

import java.io.File;
import java.io.Serializable;

import uk.ac.ebi.curtain.controller.SimpleController;
import uk.ac.ebi.curtain.management.InterceptorInfo;
import uk.ac.ebi.curtain.service.IdentifierFilepositionIndex;
import uk.ac.ebi.curtain.util.FileIndexWriter;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.data.FileType;
import uk.ac.ebi.curtain.utils.file.FileInfo;
import uk.ac.ebi.curtain.utils.io.impl.FileIO;

/**
 * Does nothing with the input
 * 
 * @author mhaimel
 *
 */
public class StartupCurtainCheck extends SimpleController<Serializable, Serializable> {
	private static Object syncObject = new Object();
	private static Boolean hasChecked = false;
	
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	protected Serializable processData(Serializable input, InterceptorInfo info) {
		syncRunChecks();
		return input;
	}
	
	private void syncRunChecks(){
		synchronized (syncObject) {
			if(!hasChecked){
				_doRunChecks();
				hasChecked = true;
			}
		}
	}

	private void _doRunChecks() {
		_checkWorkingDir();
		_checkFilePositionIndex();		
	}

	private void _checkWorkingDir() {
		File dir = getContext().currentFiles().getWorkingDir();
		if(!dir.exists() && !dir.mkdirs()){
			throw new CurtainUncheckedException("Not able to create working directory " + dir);
		}
	}

	private void _checkFilePositionIndex() {
		File cFile = getContext().currentFiles().getConfigurationInformation();
		IdentifierFilepositionIndex idx = getContext().getPositionIndex(cFile);
		if(cFile.exists()){
			idx.synchronize();
		}
		idx.setWriteOnly();
		FileIndexWriter out = null;
		try{
			out = idx.getWriter();
			for(FileInfo f : getContext().getArguments().getFiles(FileType.values())){
				Integer cat = getContext().getArguments().getCategory(f);
				out.addFile(f, cat);
				Integer insLen = getContext().getArguments().getInsertLength(f);
				Integer insSd = getContext().getArguments().getInsertLengthSd(f);
				if(null != insLen){
					out.addInsertLength(cat, insLen);
				}
				if(null != insSd){
					out.addInsertLengthSd(cat, insSd);
				}
			}
		} finally{
			FileIO.closeQuietly(out);
			FileIO.closeQuietly(idx);
		}
	}
	
}
